<template>
  <div class="image-overview-container">
    <!-- 月份选择区域 -->
    <div class="month-selection">
      <h3>请选择月份：</h3>
      <select v-model="selectedMonth" @change="onMonthChange">
        <option v-for="month in months" :key="month" :value="month">{{ month }}</option>
      </select>
    </div>

    <!-- 分隔区域，展示图片列表和表详情 -->
    <div class="content">
      <!-- 图片列表区域 -->
      <div class="image-list">
        <h3 v-if="selectedMonth">图片列表（{{ selectedMonth }}）</h3>
        <!-- 全选按钮 -->
        <button @click="selectAllImages">{{ allSelected ? '取消全选' : '全选' }}</button>
        <button @click="openTagModal">调整标签</button>
        <ul v-if="imageTables.length > 0">
          <li v-for="table in imageTables" :key="table.id">
            <label class="checkbox-container">
              <input type="checkbox" v-model="selectedImageIds" :value="table.id">
            </label>
            <span class="file-name" @click="selectTable(table)">
      {{ truncateText(table.file_name, 30) }}
    </span>
          </li>
        </ul>

        <p v-else-if="selectedMonth">暂无数据</p>
      </div>

      <!-- 表详情区域 -->
      <div class="table-details" v-if="selectedTable">
        <h3>表详情：{{ selectedTable.file_name }}</h3>
        <div class="details">
          <p><strong>图片ID：</strong> {{ selectedTable.id }}</p>
          <p><strong>文件名称：</strong> {{ selectedTable.file_name }}</p>
          <p><strong>文件路径：</strong> {{ selectedTable.file_path }} KB</p>
          <p><strong>文件日期：</strong> {{ selectedTable.file_date }}</p>
        </div>
        <div class="tag_details">
          <p><strong>标签信息：</strong> {{ tags }}</p>
        </div>
          <div class="media-preview" v-if="imageUrl">
            <h4>媒体预览：</h4>
            <img v-if="isImage(selectedTable.file_name)" :src="imageUrl" alt="图片加载失败" />
            <video v-else-if="isVideo(selectedTable.file_name)" :src="imageUrl" controls autoplay>
              您的浏览器不支持视频播放
            </video>
          </div>
      </div>
    </div>

    <!-- 分页控件 -->
    <div v-if="pageInfo" class="pagination">
      <button @click="changePage(pageInfo.pageNum - 1)" :disabled="pageInfo.pageNum <= 1">上一页</button>

      <span v-for="page in visiblePages" :key="page">
        <button @click="changePage(page)" :class="{ active: page === pageInfo.pageNum }">
          {{ page }}
        </button>
      </span>

      <button @click="changePage(pageInfo.pageNum + 1)" :disabled="pageInfo.pageNum >= pageInfo.pages">下一页</button>

      <select v-model="pageSize" @change="changePage(1)">
        <option v-for="size in [10, 20, 30, 50]" :key="size" :value="size">{{ size }} 条/页</option>
      </select>
    </div>
    <!-- 标签选择弹框 -->
    <!-- 标签选择弹框 -->
    <div v-if="showTagModal" class="tag-modal">
      <div class="tag-modal-content">
        <h3>选择标签</h3>
        <button @click="closeTagModal">关闭</button>

        <!-- 已选择标签区域 -->
        <div class="selected-tags">
          <h4>已选择标签：</h4>
          <ul class="scrollable">
            <li v-for="tag in selectedTags" :key="tag.tagId">
              {{ tag.tagName }}
              <button @click="removeSelectedTag(tag)">x</button>
            </li>
          </ul>
          <!-- 提交按钮 -->
          <button @click="submitTags(1)">提交标签</button>
          <button @click="submitTags(0)">删除标签</button>
        </div>

        <!-- 一级标签 -->
        <div>
          <h4>一级标签</h4>
          <ul class="scrollable">
            <li v-for="tag in level1Tags" :key="tag.tagId" @click="selectLevel1Tag(tag)">
              {{ tag.tagName }}
              <button @click="addSelectedTag(tag)">√</button>
            </li>
          </ul>
        </div>

        <!-- 二级标签 -->
        <div v-if="selectedLevel1Tag">
          <h4>二级标签</h4>
          <ul class="scrollable">
            <li v-for="tag in level2Tags" :key="tag.tagId" @click="selectLevel2Tag(tag)">
              {{ tag.tagName }}
              <button @click="addSelectedTag(tag)">√</button>
            </li>
          </ul>
        </div>

        <!-- 三级标签 -->
        <div v-if="selectedLevel2Tag">
          <h4>三级标签</h4>
          <ul class="scrollable">
            <li v-for="tag in level3Tags" :key="tag.tagId" @click="selectLevel2Tag(tag)">
              {{ tag.tagName }}
              <button @click="addSelectedTag(tag)">√</button>
            </li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {getAllFileMonth,getImageUrl,getImageTableByFileMonth,getTagLine,fetchLevel1Tags, fetchLevel2Tags,addImageTag,deleteImageTag} from '@/components/js/ImageService'; // 导入 tagService

export default {
  name: 'ImageOverview',
  data() {
    return {
      months: [], // 存放所有月份
      imageTables: [], // 存放选定月份的表数据
      selectedMonth: null, // 选中的月份
      selectedTable: null, // 选中的表
      imageUrl: null, // 选中的图片URL
      tags: '', // 选中的标签信息
      pageInfo: null, // 分页信息
      pageSize: 10, // 默认每页显示 30 条
      selectedImageIds: [], // 存储勾选的图片id
      allSelected: false, // 是否全选
      level1Tags: [], // 一级标签
      level2Tags: [], // 二级标签
      level3Tags: [], // 三级标签
      selectedLevel1Tag: null, // 当前选择的一级标签
      selectedLevel2Tag: null, // 当前选择的二级标签
      selectedLevel3Tags: [], // 当前选择的三级标签
      showTagModal: false, // 控制标签弹窗显示
      selectedTags: [], // 存储已选择的标签
    };
  },
  computed: {
    // 计算可见页码范围（最多显示 10 页）
    visiblePages() {
      if (!this.pageInfo) return [];
      const totalPages = this.pageInfo.pages;
      const currentPage = this.pageInfo.pageNum;
      const maxVisible = 10;

      let start = Math.max(1, currentPage - Math.floor(maxVisible / 2));
      let end = Math.min(totalPages, start + maxVisible - 1);

      if (end - start < maxVisible - 1) {
        start = Math.max(1, end - maxVisible + 1);
      }

      return Array.from({ length: end - start + 1 }, (_, i) => start + i);
    }
  },
  methods: {
    // 获取所有月份
    async fetchMonths() {
      try {
        this.months = await getAllFileMonth();
      } catch (error) {
        console.error('获取月份列表失败:', error);
      }
    },
    // 获取标签信息
    async fetchTags(imageId) {
      try {
        this.tags = await getTagLine(imageId);
      } catch (error) {
        console.error('获取标签列表失败:', error);
      }
    },

    // 选择月份并获取对应的图片表数据
    async selectMonth(month) {
      this.selectedMonth = month;
      this.selectedTable = null;
      this.imageUrl = null;
      this.pageInfo = null; // 清空分页信息
      await this.fetchImageTables(month, 1); // 默认请求第一页数据
    },

    // 选择月份后触发
    onMonthChange() {
      this.selectMonth(this.selectedMonth);
    },

    // 获取选定月份的图片表数据并处理分页
    async fetchImageTables(month, pageNum) {
      try {
        const response = await getImageTableByFileMonth(pageNum,this.pageSize,month);
        if (response.data && response.data.list) {
          this.imageTables = response.data.list;
          this.pageInfo = response.data; // 获取分页信息
        } else {
          console.error('接口返回的图片表数据格式不正确');
          this.imageTables = [];
          this.pageInfo = null;
        }
      } catch (error) {
        console.error('获取图片表失败:', error);
        this.imageTables = [];
        this.pageInfo = null;
      }
    },

    // 选择图片表并显示详情
    async selectTable(table) {
      this.selectedTable = table;
      this.imageUrl = getImageUrl(table.id);
      this.fetchTags(table.id);
    },

    isImage(url) {
      return /\.(jpg|jpeg|png|gif|webp)$/i.test(url);
    },
    isVideo(url) {
      return /\.(mov|mp4|avi|webm)$/i.test(url);
    },

    // 截断文本，防止超长显示
    truncateText(text, maxLength) {
      return text.length > maxLength ? text.substring(0, maxLength) + '...' : text;
    },

    // 分页切换
    changePage(pageNum) {
      if (pageNum >= 1 && this.pageInfo && pageNum <= this.pageInfo.pages) {
        this.fetchImageTables(this.selectedMonth, pageNum);
      }
    },
    // 切换单个图片选中状态
    toggleImageSelection() {
      this.allSelected = this.selectedImageIds.length === this.imageTables.length;
    },

    // 全选/取消全选
    selectAllImages() {
      if (this.allSelected) {
        this.selectedImageIds = []; // 取消全选
      } else {
        this.selectedImageIds = this.imageTables.map((table) => table.id); // 选中所有图片
      }
      this.allSelected = !this.allSelected;
    },
    // 打开标签弹框
    async openTagModal() {
      if (this.selectedImageIds.length === 0) {
        alert("请先选择图片！");
        return;
      }
      this.showTagModal = true;
      await this.fetchLevel1Tags(); // 先获取一级标签
    },

    // 关闭标签弹框
    closeTagModal() {
      this.showTagModal = false;
      this.selectedLevel1Tag = null;
      this.selectedLevel2Tag = null;
      this.selectedLevel3Tags = [];
      this.selectedTags = [];
    },

    // 获取一级标签
    async fetchLevel1Tags() {
      try {
        this.level1Tags = await fetchLevel1Tags();
      } catch (error) {
        console.error("获取一级标签失败:", error);
      }
    },

    async selectLevel1Tag(tag) {
      this.selectedLevel1Tag = tag;
      this.selectedLevel2Tag = null;
      this.selectedLevel3Tags = [];
      // this.addSelectedTag(tag); // 添加一级标签到已选择列表
      try {
        this.level2Tags = await fetchLevel2Tags(tag.tagId);
      } catch (error) {
        console.error("获取二级标签失败:", error);
      }
    },

    async selectLevel2Tag(tag) {
      this.selectedLevel2Tag = tag;
      this.selectedLevel3Tags = [];
      // this.addSelectedTag(tag); // 添加二级标签到已选择列表
      try {
        this.level3Tags = await fetchLevel2Tags(tag.tagId);
      } catch (error) {
        console.error("获取三级标签失败:", error);
      }
    },
    // 添加标签到已选择列表
    addSelectedTag(tag) {
      if (!this.selectedTags.some(t => t.tagId === tag.tagId)) {
        this.selectedTags.push(tag);
      }
    },

    // 从已选择列表中移除标签
    removeSelectedTag(tag) {
      this.selectedTags = this.selectedTags.filter(t => t.tagId !== tag.tagId);
    },
    // 提交标签
    async submitTags(flag) {
      if (this.selectedTags.length === 0) {
        alert("请选择至少一个标签！");
        return;
      }

      // 封装数据
      const imageTagBeans = this.selectedImageIds.map(imageId =>
          this.selectedTags.map(tag => ({
            id: null, // id 为空
            imageId,
            tagId: tag.tagId
          }))
      ).flat();

      try {
        if (flag === 0) {
          await deleteImageTag(imageTagBeans);
        } else if (flag === 1) {
          await addImageTag(imageTagBeans);
        }
        this.closeTagModal();
      } catch (error) {
        console.error("调整标签失败:", error);
      }
    }

  },
  mounted() {
    this.fetchMonths();
  }
};
</script>

<style scoped>
@import '@/css/styles.css';
</style>
